<?
include_once 'include/processes.php';
$Login_Process = new Login_Process;
$Login_Process->check_status($_SERVER['SCRIPT_NAME']);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Crash Report</title>
<link href="include/style.css" rel="stylesheet" type="text/css">
<body>

<div class="center">
<?php 

function checkCrashFile() 
{
	if (empty($_FILES['crash_file'])) {
		echo "<p>QA Report Error: No crash file!</p>";
		return false;
	}	
	if ($_FILES['crash_file']['error'] != 0) {
		echo "<p>QA Report Error: Crash file corrupted!</p>";
		return false;
	}
	return true;
}

function checkText()
{
	$commentText = strval($_POST['comment_text']);
	if (!$commentText) {
		return;
	}

	//echo "<p>".$commentText."</p>";
	return true;
}

function storeCrashComment()
{
	$crashFilePath = tempnam("/tmp", "crash");	
	
	if (!move_uploaded_file($_FILES['crash_file']['tmp_name'], $crashFilePath)) {
		echo "<p>QA Report Error : Failed to save the crash file.</p>";
		return;
	}

    $fileHandle = fopen($crashFilePath, "r"); 
    if (!$fileHandle) {
        echo("<p>QA Report Error : Internal Error</p>");
		unlink($crashFilePath);
        return;
    }

	$addrStr = "";
    while (!feof($fileHandle)) {
        $buffer = fgets($fileHandle, 4096); // read a line  
		if (preg_match("/Exception Addr/i", $buffer)) {
			$pos = strpos($buffer, ": ");
			$addrStr = substr($buffer, $pos + 9);
			$addrStr = trim($addrStr);
			break;
		}	
    }
	//echo "<p>address string[".$addrStr."]</p>";

	$commentText = $_POST['comment_text'];
	
	$lp = new Login_Process;
	$ret = $lp->Update_Crash_Report($addrStr, $commentText, $_SESSION['username']);
	if ($ret) {
		//$link = "<a href=""view_comments.php?cid=$addrStr"">Here</a>";
		$link = "";
		$link = '<a href="view_comments.php?crash_addr='.$addrStr.'">Here</a>';
		echo "<p>Thank you for reporting!</p>";
		echo "<p>Click $link to read comments for crash $addrStr.</p>";		
	} else {
		echo "<p>Report failed.</p>";
	}

	unlink($crashFilePath);
}

if (checkCrashFile() && checkText()) {
	storeCrashComment();
}

?>
</div>

<div class="center">
<a href="main.php">Back to main</a> | <a href="view_dumps.php">View Dumps</a>
</div>

</body>
</html>

